<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { formatDate } from '../../utils/format'

// 基础表格数据
const tableData = ref([
  {
    id: 1,
    date: '2023-05-03',
    name: '张三',
    address: '北京市朝阳区芍药居',
    status: 'success',
    tag: '家庭地址'
  },
  {
    id: 2,
    date: '2023-05-02',
    name: '李四',
    address: '北京市海淀区西二旗',
    status: 'warning',
    tag: '公司地址'
  },
  {
    id: 3,
    date: '2023-05-01',
    name: '王五',
    address: '上海市浦东新区张江',
    status: 'danger',
    tag: '公司地址'
  },
  {
    id: 4,
    date: '2023-04-30',
    name: '赵六',
    address: '广州市天河区珠江新城',
    status: 'info',
    tag: '家庭地址'
  }
])

// 选中行数据
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
    `确认删除用户 ${row.name} 的记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      tableData.value.splice(index, 1)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 删除选中行
const deleteSelected = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(
    `确认删除选中的 ${multipleSelection.value.length} 条记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const ids = multipleSelection.value.map(item => item.id)
      tableData.value = tableData.value.filter(item => !ids.includes(item.id))
      ElMessage({
        type: 'success',
        message: '批量删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 分页表格数据
const paginationTableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 生成模拟数据
const generateData = () => {
  const result = []
  const cities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '武汉', '成都']
  const types = ['家庭地址', '公司地址', '临时地址', '收货地址']
  const statuses = ['success', 'warning', 'danger', 'info']
  
  for (let i = 1; i <= 100; i++) {
    const city = cities[Math.floor(Math.random() * cities.length)]
    const street = `${city}市${Math.floor(Math.random() * 10) + 1}区${Math.floor(Math.random() * 100) + 1}街`
    result.push({
      id: i,
      date: new Date(2023, 4, Math.floor(Math.random() * 30) + 1).toISOString().slice(0, 10),
      name: `用户${i}`,
      address: street,
      tag: types[Math.floor(Math.random() * types.length)],
      status: statuses[Math.floor(Math.random() * statuses.length)]
    })
  }
  
  return result
}

// 加载表格数据
const loadData = () => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    const allData = generateData()
    total.value = allData.length
    
    // 分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    paginationTableData.value = allData.slice(start, end)
    
    loading.value = false
  }, 500)
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadData()
}

// 可编辑表格
const editableTableData = ref([
  {
    id: 1,
    name: '张三',
    age: 24,
    email: 'zhangsan@example.com',
    address: '北京朝阳区',
    edit: false,
    originalAddress: '北京朝阳区'
  },
  {
    id: 2,
    name: '李四',
    age: 30,
    email: 'lisi@example.com',
    address: '上海浦东新区',
    edit: false,
    originalAddress: '上海浦东新区'
  },
  {
    id: 3,
    name: '王五',
    age: 27,
    email: 'wangwu@example.com',
    address: '广州天河区',
    edit: false,
    originalAddress: '广州天河区'
  }
])

const editingRow = ref(null)
const editForm = reactive({
  name: '',
  age: '',
  email: '',
  address: ''
})

// 开始编辑行
const startEdit = (row) => {
  editingRow.value = row.id
  Object.assign(editForm, row)
  row.originalAddress = row.address
  row.edit = true
}

// 保存编辑
const saveEdit = (index) => {
  // 简单验证
  if (!editForm.name || !editForm.email) {
    ElMessage.error('姓名和邮箱不能为空')
    return
  }
  
  Object.assign(editableTableData.value[index], editForm)
  editingRow.value = null
  ElMessage.success('保存成功')
}

// 取消编辑
const cancelEdit = (row) => {
  editingRow.value = null
  row.address = row.originalAddress
  row.edit = false
}

// 初始化
onMounted(() => {
  loadData()
})

// 可排序表格数据
const sortableTableData = ref([
  {
    date: '2023-05-01',
    name: '张三',
    age: 25,
    address: '北京市朝阳区芍药居'
  },
  {
    date: '2023-05-02',
    name: '李四',
    age: 32,
    address: '北京市海淀区西二旗'
  },
  {
    date: '2023-05-03',
    name: '王五',
    age: 28,
    address: '上海市浦东新区张江'
  },
  {
    date: '2023-05-04',
    name: '赵六',
    age: 35,
    address: '广州市天河区珠江新城'
  },
  {
    date: '2023-05-05',
    name: '钱七',
    age: 29,
    address: '深圳市南山区科技园'
  }
])

// 高级表格数据（用于分页示例）
const advancedTableData = ref([])
const search = ref('')

// 过滤后的数据
const filteredAdvancedTableData = computed(() => {
  if (!search.value) {
    return advancedTableData.value
  }
  return advancedTableData.value.filter(
    (data) =>
      data.name.includes(search.value) ||
      data.address.includes(search.value) ||
      data.status.includes(search.value)
  )
})

// 分页后的数据
const paginatedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredAdvancedTableData.value.slice(start, end)
})

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const formRef = ref(null)
const formData = reactive({
  id: null,
  name: '',
  age: 30,
  date: '',
  address: '',
  status: '活跃'
})
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'change' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在1到120之间', trigger: 'change' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取状态对应的标签类型
const statusTagType = (status) => {
  switch (status) {
    case '活跃':
      return 'success'
    case '禁用':
      return 'danger'
    case '审核中':
      return 'warning'
    default:
      return 'info'
  }
}

// 排序变更处理
const handleSortChange = ({ prop, order }) => {
  if (!prop || !order) return
  
  sortableTableData.value.sort((a, b) => {
    const aVal = a[prop]
    const bVal = b[prop]
    
    if (order === 'ascending') {
      return aVal < bVal ? -1 : aVal > bVal ? 1 : 0
    } else {
      return aVal > bVal ? -1 : aVal < bVal ? 1 : 0
    }
  })
  
  ElMessage({
    message: `按${prop}字段${order === 'ascending' ? '升序' : '降序'}排列`,
    type: 'success'
  })
}

// 搜索变更
const handleSearchChange = () => {
  currentPage.value = 1
}

// 添加记录
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(formData).forEach(key => {
    if (key in row) {
      formData[key] = row[key]
    }
  })
  dialogVisible.value = true
}

// 查看记录
const handleView = (row) => {
  ElMessage({
    message: `查看记录: ${JSON.stringify(row)}`,
    type: 'info'
  })
}

// 提交表单
const handleSubmit = () => {
  if (!formRef.value) return
  
  formRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 添加新记录
        const newId = Math.max(...advancedTableData.value.map(item => item.id), 0) + 1
        const newRecord = { ...formData, id: newId }
        
        // 格式化日期（如果需要）
        if (newRecord.date instanceof Date) {
          newRecord.date = formatDate(newRecord.date, 'YYYY-MM-DD')
        }
        
        advancedTableData.value.unshift(newRecord)
        ElMessage({
          message: '添加成功',
          type: 'success'
        })
      } else {
        // 更新记录
        const index = advancedTableData.value.findIndex(item => item.id === formData.id)
        if (index !== -1) {
          // 格式化日期（如果需要）
          const updatedRecord = { ...formData }
          if (updatedRecord.date instanceof Date) {
            updatedRecord.date = formatDate(updatedRecord.date, 'YYYY-MM-DD')
          }
          
          advancedTableData.value[index] = updatedRecord
          ElMessage({
            message: '更新成功',
            type: 'success'
          })
        }
      }
      dialogVisible.value = false
    } else {
      ElMessage({
        message: '请检查表单填写是否正确',
        type: 'warning'
      })
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.id = null
  formData.name = ''
  formData.age = 30
  formData.date = new Date()
  formData.address = ''
  formData.status = '活跃'
}

// 生命周期钩子
onMounted(() => {
  loading.value = true
  // 模拟异步加载
  setTimeout(() => {
    advancedTableData.value = generateData()
    loading.value = false
  }, 500)
})
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-main>
        <!-- 基础表格 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>基础表格</span>
            </div>
          </template>

          <div class="table-description">
            <p>基础的表格展示用法</p>
          </div>

          <el-table
            :data="tableData"
            style="width: 100%"
            border
            stripe
            highlight-current-row
          >
            <el-table-column prop="date" label="日期" width="180" />
            <el-table-column prop="name" label="姓名" width="180" />
            <el-table-column prop="address" label="地址" />
          </el-table>
        </el-card>

        <!-- 可选择表格 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>可选择表格</span>
            </div>
          </template>

          <div class="table-description">
            <p>支持多选和单选的表格</p>
          </div>

          <div class="operation-bar mb-10">
            <el-button type="primary" size="small" @click="handleSelectionAll">全选</el-button>
            <el-button type="danger" size="small" @click="handleClearSelection">清空选择</el-button>
            <el-button type="success" size="small" @click="handleBatchOperation" :disabled="multipleSelection.length === 0">
              批量操作 (已选择 {{ multipleSelection.length }} 项)
            </el-button>
          </div>

          <el-table
            ref="multipleTableRef"
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="date" label="日期" width="180" />
            <el-table-column prop="name" label="姓名" width="180" />
            <el-table-column prop="address" label="地址" />
          </el-table>
        </el-card>

        <!-- 可排序表格 -->
        <el-card class="box-card mb-20">
          <template #header>
            <div class="card-header">
              <span>可排序表格</span>
            </div>
          </template>

          <div class="table-description">
            <p>对表格进行排序，对应列设置 sortable 属性即可</p>
          </div>

          <el-table
            :data="sortableTableData"
            style="width: 100%"
            border
          >
            <el-table-column prop="date" label="日期" width="180" sortable />
            <el-table-column prop="name" label="姓名" width="180" sortable />
            <el-table-column prop="age" label="年龄" width="100" sortable />
            <el-table-column prop="address" label="地址" />
          </el-table>
        </el-card>

        <!-- 可操作表格 -->
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>可操作表格</span>
              <div class="operation-group">
                <el-button type="primary" size="small" @click="handleAddRow">新增行</el-button>
                <el-input
                  v-model="searchKeyword"
                  placeholder="请输入关键字搜索"
                  style="width: 200px"
                  clearable
                  @clear="handleSearch"
                  @input="handleSearch"
                >
                  <template #append>
                    <el-button :icon="Search" @click="handleSearch" />
                  </template>
                </el-input>
              </div>
            </div>
          </template>

          <div class="table-description">
            <p>带有操作列的表格示例，可进行编辑、删除等操作</p>
          </div>

          <el-table
            :data="filteredTableData"
            style="width: 100%"
            border
            v-loading="loading"
          >
            <el-table-column prop="date" label="日期" width="180" />
            <el-table-column prop="name" label="姓名" width="180" />
            <el-table-column prop="address" label="地址" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="handleEdit(scope.$index, scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                >
                  删除
                </el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="handleView(scope.row)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="filteredTableData.length"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>

        <!-- 编辑对话框 -->
        <el-dialog v-model="dialogFormVisible" title="编辑信息" width="30%">
          <el-form :model="form" label-width="80px">
            <el-form-item label="日期">
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="form.address" type="textarea" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="saveEditForm">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}
.mb-10 {
  margin-bottom: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.table-description {
  margin-bottom: 15px;
  color: #666;
}
.operation-bar {
  margin-bottom: 15px;
}
.operation-group {
  display: flex;
  gap: 10px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 